﻿using System;
using System.Web.UI.WebControls;

namespace ECommerce.Controls
{
	public partial class TopSellingProducts : BaseUserControl
	{
		private Service.IProductService _ProductService;

		protected void Page_Load(object sender, EventArgs e)
		{
			BindData();
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			this.LTopSellingProductsTitle.Text = GetLocalResourceString("TopSellingProducts.Title");
		}

		protected void RepeaterTopSellingProducts_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if (e.Item.DataItem != null)
			{
				var dateItem = e.Item.DataItem as Data.Entity.Product;
				var HyperLinkProdImg = e.Item.FindControl("HyperLinkProdImg") as HyperLink;
				var HyperLinkProdName = e.Item.FindControl("HyperLinkProdName") as HyperLink;
				var LiteralProdPrice = e.Item.FindControl("LiteralProdPrice") as Literal;

				var url = "~/ProductDetail.aspx?productid=" + dateItem.ProductID.ToString();
				var productName = dateItem.Name.Length > 15 ? dateItem.Name.Substring(0, 15) + "..." : dateItem.Name;

				HyperLinkProdName.Text = productName;
				HyperLinkProdName.NavigateUrl = url;
				HyperLinkProdName.ToolTip = dateItem.Name;

				HyperLinkProdImg.NavigateUrl = url;
				HyperLinkProdImg.ImageUrl = "~/PictureHandler.ashx?picturesize=48&productid=" + dateItem.ProductID;
				HyperLinkProdImg.ToolTip = dateItem.Name;

				LiteralProdPrice.Text = dateItem.ListPrice.Value.ToString("c2");
			}
		}

		private void BindData()
		{
			if (_ProductService == null)
			{
				_ProductService = new Service.ProductService();
			}
			var data = _ProductService.GetTopSellingProducts();

			RepeaterTopSellingProducts.DataSource = data;
			RepeaterTopSellingProducts.DataBind();
		}
	}
}